<template>
  <el-dialog
    :model-value="visible"
    :title="dialogTitle"
    @close="handleClose"
    :before-close="handleBeforeClose"
    destroy-on-close
  >
    <el-form
      :model="userForm"
      ref="userFormRef"
      :rules="formRules"
      label-width="100px"
      scroll-to-error
    >
      <el-form-item label="账号" prop="username">
        <el-input v-model="userForm.username" clearable />
      </el-form-item>
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="userForm.name" clearable />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="userForm.phone" clearable />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="userForm.sex" clearable>
          <el-option :value="'1'" :label="'男'" />
          <el-option :value="'0'" :label="'女'" />
        </el-select>
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input v-model="userForm.idNumber" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose" :loading="btnLoading">取消</el-button>
      <el-button @click="resetUserForm" :loading="btnLoading">重置表单</el-button>
      <el-button type="primary" @click="submitForm" :loading="btnLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { User, getUseFormRules } from '../config/constant'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  currentUser: {
    type: Object
  },
  dialogTitle: {
    type: String,
    required: true
  },
  //'0'：新增 '1'编辑 '2'仅查看
  dialogType: {
    type: String,
    required: true
  }
})

// 子组件通知父组件处理
const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'submit', user: User, type: string): void
}>()

const userFormRef = ref()
// 表单校验规则 - 该函数单独抽取到配置文件
const formRules = getUseFormRules()
const userForm = ref<User>({
  id: '',
  username: '',
  name: '',
  phone: '',
  sex: '',
  idNumber: '' // 身份证
})

// 没有执行 onMounted -- 在首页就执行了。在打开弹窗时不会执行
watch(
  () => props.visible,
  () => {
    if (props.visible && props.currentUser?.id) {
      console.log('子组件watch 执行', props)
      // userForm.value = { ...props.currentUser }

      userForm.value.id = props.currentUser.id
      userForm.value.username = props.currentUser.username
      userForm.value.name = props.currentUser.name
      userForm.value.phone = props.currentUser.phone
      userForm.value.sex = props.currentUser.sex
      userForm.value.idNumber = props.currentUser.idNumber
    }
  }
)

// 用来判断是否阻止弹窗关闭 - 可有也可没有。如让用户确认是否已保存数据
const handleBeforeClose = (done: (isConfirm?: boolean) => void) => {
  ElMessageBox.prompt('关闭弹窗前的确认', 'Tip', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^(?!\s*$).+/,
    inputErrorMessage: '请填写输入框'
  })
    .then(({ value }) => {
      done()
    })
    .catch(() => {})
}

// 子组件关闭弹窗时的处理
const handleClose = () => {
  // 关闭弹窗
  emit('update:visible', false)

  // 清空表单的数据。避免打开新增弹窗直接回显上次的用户信息
  userForm.value = {
    id: '',
    username: '',
    name: '',
    phone: '',
    sex: '',
    idNumber: ''
  }

  // 重置表单的校验警告
  userFormRef.value?.clearValidate()
  console.log('子组件关闭弹窗函数')
}

// 重置表单为初始状态
const resetUserForm = () => {
  userFormRef.value?.resetFields()
}

// 当前弹窗所有按钮的 loading
const btnLoading = ref(false)
const submitForm = async () => {
  const valid = await userFormRef.value?.validate()

  if (!valid) {
    // 给用户提示或其他逻辑处理
    return ElMessage.error('表单验证失败，请检查输入')
  }

  if (valid) {
    btnLoading.value = true
    try {
      emit('submit', userForm.value, props.dialogType)
      handleClose()
    } catch (error) {
    } finally {
      btnLoading.value = false
    }
  }
}

// 暴露方法或属性给父组件 - 需要子组件定义过该方法
defineExpose({
  // 子组件随便创建的方法或变量
  getFormValue: () => userForm.value,
  handleClose
})
</script>
